<?php
namespace app\index\controller\wanlshop;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Db;
use think\Exception;

use think\exception\PDOException;
use think\exception\ValidateException;

use addons\wanlshop\library\WanlChat\WanlChat;
use app\common\controller\Wanlshop;
use addons\wanlshop\library\WanlSdk\Ehund; //快递100订阅

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Wanlshop
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    /**
     * Order模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\index\model\wanlshop\Order;
        $kuaidi = new \app\index\model\wanlshop\Kuaidi;
		$this->wanlchat = new WanlChat();
        $this->view->assign("kuaidiList", $kuaidi->field('name,code')->select());
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("statesList", $this->model->getStatesList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null, 10);
            $total = $this->model
                    ->with(['user','ordergoods'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user','ordergoods'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['id','username','nickname','avatar']);
				$row->pay = model('app\index\model\wanlshop\Pay')
					->where(['order_id' => $row['id'], 'type' => 'goods'])
					->field('pay_no, price, order_price, freight_price, discount_price, actual_payment')
					->find();
            }
            $list = collection($list)->toArray();
			
			
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 详情
     */
    public function detail($id = null, $order_no = null)
    {
    	$where = $order_no ? ['order_no' => $order_no] : ['id' => $id];
        $row = $this->model
    		->where($where)
    		->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 判断权限
        if ($row['shop_id'] != $this->shop->id) {
            $this->error(__('You have no permission'));
        }
        $row['address'] = model('app\index\model\wanlshop\OrderAddress')
            ->where(['order_id' => $row['id'], 'shop_id' => $this->shop->id])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();
			
		$row['pay'] = model('app\index\model\wanlshop\Pay')
			->where(['order_id' => $row['id'], 'type' => 'goods'])
			->find();
			
		// 查询快递状态
		switch ($row['state']) {
			case 1:
				$express = [
					'context' => '付款后，即可将宝贝发出',
					'status' => '尚未付款',
					'time' => date('Y-m-d H:i:s', $row['createtime'])
				];
				break;
			case 2:
				$express = [
					'context' => '商家正在处理订单',
					'status' => '已付款',
					'time' => date('Y-m-d H:i:s', $row['paymenttime'])
				];
				break;
			default: // 获取物流
				$eData = model('app\api\model\wanlshop\KuaidiSub')
					->where(['express_no' => $row['express_no']])
					->find();
				// 获取数据 兼容PHP7.4	1.1.5升级
				if(!empty($eData['data'])){
					$ybData = json_decode($eData['data'], true);
					// 运单状态 1.0.6升级
					$statusText = ['在途','揽收','疑难','签收','退签','派件','退回','转投'];
					$status = $statusText[0];
					if(in_array('status', $ybData[0])){
						$status = $ybData[0]['status'];
					}else{
						if($eData['ischeck'] === 1){
							$status = $statusText[3];
						}else{
							$status = $statusText[$eData['state']];
						}
					}
					$express = [
						'status' => $status,
						'context' => $ybData[0]['context'],
						'time' => $ybData[0]['time'],
					];
				}else{
					$express = [
						'status' => '已发货',
						'context' => '包裹正在等待快递小哥揽收~',
						'time' => date('Y-m-d H:i:s', $row['delivertime'])
					];
				}
		}
		$this->view->assign("kuaidi", $express);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
	
	/**
	 * 快递查询
	 */
	public function relative($id = null)
	{
		$row = $this->model->get($id);
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		// 判断权限
		if ($row['shop_id'] != $this->shop->id) {
		    $this->error(__('You have no permission'));
		}
		$data = model('app\index\model\wanlshop\KuaidiSub')
			->where(['express_no' => $row['express_no']])
			->find();
		$list = [];
		$week = array("0"=>"星期日","1"=>"星期一","2"=>"星期二","3"=>"星期三","4"=>"星期四","5"=>"星期五","6"=>"星期六");
		if($data){
			// 兼容PHP7.4	1.1.5升级
			$data = json_decode($data['data'], true);
			if(!empty($data)){
                foreach($data as $vo){
                    $list[] = [
                        'time' => strtotime($vo['time']),
                        'status' => in_array('status', $vo) ? $vo['status'] : '在途', // 1.0.6升级
                        'context' => $vo['context'],
                        'week' => $week[date('w', strtotime($vo['time']))]
                    ];
                }
            }
		}
		$this->view->assign("week", $week);
		$this->view->assign("list", $list);
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
	
    
    /**
     * 打印发货单 1.1.2升级
     */
    public function invoice($ids = null)
    {
        $list = $this->model->all($ids);
        if (!$list) {
            $this->error(__('No Results were found'));
        }
        foreach ($list as $row) {
            // 判断权限
            if ($row['shop_id'] != $this->shop->id) {
                $this->error(__('You have no permission'));
            }
            $row['address'] = model('app\index\model\wanlshop\OrderAddress')
                ->where(['order_id' => $row['id'], 'shop_id' => $this->shop->id])
                ->order('isaddress desc')
                ->field('id,name,mobile,address,address_name')
                ->find();
            // 发件人信息
            $row['shopConfig'] = model('app\api\model\wanlshop\ShopConfig')
                ->where(['shop_id' => $this->shop->id])
                ->field('sendPhoneNum,sendCity')
                ->find();
    		$row['pay'] = model('app\index\model\wanlshop\Pay')
    			->where(['order_id' => $row['id'], 'type' => 'goods'])
    			->field('id,number,actual_payment,order_price,freight_price,discount_price,price')
    			->find();
        }
        $this->view->assign("row", $list);
        return $this->view->fetch();
    }
    
    /**
     * 发货 & 批量发货
     */
    public function delivery($ids = null)
    {
        $data = [];
        $lists = [];
        $row = $this->model->all($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        foreach ($row as $vo) {
            if ($vo['shop_id'] != $this->shop->id) {
                $this->error(__('You have no permission'));
            }
            $vo['address'] = model('app\index\model\wanlshop\OrderAddress')
                ->where(['order_id' => $vo['id'], 'shop_id' => $this->shop->id])
                ->order('isaddress desc')
                ->field('id,name,mobile,address,address_name')
                ->find();
            if ($vo['state'] == 2) {
                $lists[] = $vo;
            } else {
                $data[] = $vo;
            }
        }
        if ($this->request->isAjax()) {
            $request = $this->request->post();
            if (!array_key_exists("order", $request['row'])) {
                $this->success(__('没有发现可以发货订单~'));
            }
			/*if(!$this->wanlchat->isWsStart()){
				$this->error('平台未启动IM即时通讯服务，暂时不可以发货');
			}*/
            $config = get_addon_config('wanlshop');
            $ehund = new Ehund($config['kuaidi']['secretKey'], $config['ini']['appurl'].$config['kuaidi']['callbackUrl']);
            $order = [];
			$express = [];
			foreach ($request['row']['order']['id'] as $key => $id) {
                $express_no = $request['row']['order']['express_no'][$key];
                $express_name = $request['row']['express_name'];
                $order[] = [
                    'id' => $id,
                    'express_name' => $express_name,
                    'express_no' => $express_no,
                    'delivertime' => time(),
                    'state' => 3
                ];
				// 1.0.5升级 查询是否存在,如果存在绕过快递100订阅
				$is_express_no = model('app\index\model\wanlshop\KuaidiSub')->where(['express_no' => $express_no])->count();
                // 订阅快递查询
                if ($config['kuaidi']['secretKey'] && $is_express_no == 0) {
                    $returncode = $ehund->subScribe($express_name, $express_no);
                    if ($returncode['returnCode'] != 200 && $express_name != 'ziti') {
                        $this->error('快递订阅接口异常-'.$returncode['message']);
                    }
                    $express[] = [
                        'sign' => $ehund->sign($express_no),
                        'express_no' => $express_no,
                        'returncode' => $returncode['returnCode'],
                        'message' => $returncode['message']
                    ];
                }
				// 推送消息
//				$this->pushOrder($id,'已发货');
            }
			// 使用事务 1.1.2升级
			$result = false;
			Db::startTrans();
			try {
			  	$result = $this->model->saveAll($order);
			  	// 写入快递订阅列表
			  	if ($express) model('app\index\model\wanlshop\KuaidiSub')->saveAll($express);
				Db::commit();
			} catch (PDOException $e) {
			    Db::rollback();
			    $this->error($e->getMessage());
			} catch (Exception $e) {
			    Db::rollback();
			    $this->error($e->getMessage());
			}
			// 判断是否支付成功
			if($result){
				$this->success();
			}else{
				$this->error('网络异常，发货失败');
			}
        }
        $this->view->assign("lists", $lists); //可以发货
        $this->view->assign("data", $data);
        return $this->view->fetch();
    }

    /**
     * 导出发货单excel
     */
    public function exportDeliveryExcel()
    {
        $ids = $this->request->get()['ids'];
        if(!$ids){
            $this->error('订单ID不能为空');
        }
        $orderIdList = explode(',', $ids);
        if(!$orderIdList){
            $this->error('订单ID不能为空');
        }

        // 创建一个新的电子表格对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        //将第一行单元格设置成粗体
        $sheet->getStyle('A1:M1')->getFont()->setBold(true);

        //宽度自适应
        $sheet->getDefaultColumnDimension()->setWidth(20);

        // 添加标题
        $sheet->setCellValue('A1', '订单号');
        $sheet->setCellValue('B1', '收件人姓名');
        $sheet->setCellValue('C1', '收件人手机');
        $sheet->setCellValue('D1', '收件人电话');
        $sheet->setCellValue('E1', '收件人省');
        $sheet->setCellValue('F1', '收件人市');
        $sheet->setCellValue('G1', '收件人区');
        $sheet->setCellValue('H1', '收件人详细地址');
        $sheet->setCellValue('I1', '发件人手机');
        $sheet->setCellValue('J1', '发件人市');
        $sheet->setCellValue('K1', '运单号');
        $sheet->setCellValue('L1', '快递公司');
        $sheet->setCellValue('M1', '商品名称');

        $index = 2;
        foreach ($orderIdList as $id) {
            if(!$id) {
                break;
            }

            $order = model('app\index\model\wanlshop\Order')
                ->where(['id' => $id, 'shop_id' => $this->shop->id])
                ->field('id, order_no')
                ->find();
            if(!$order) {
                $this->error('订单不存在');
            }
            $sheet->setCellValue('A' . $index, 'SHOP' . $order['order_no']);

            $address = model('app\index\model\wanlshop\OrderAddress')
                ->where(['order_id' => $id, 'shop_id' => $this->shop->id])
                ->order('isaddress desc')
                ->field('id,name,mobile,address,address_name')
                ->find();
            $sheet->setCellValue('B' . $index, $address["name"]);
            $sheet->setCellValue('C' . $index, $address["mobile"]);
            $sheet->setCellValue('D' . $index, "");

            // 分割获取省市区
            $addressArr = explode('/', $address["address"]);
            $sheet->setCellValue('E' . $index, $addressArr[0]);
            $sheet->setCellValue('F' . $index, $addressArr[1]);
            $sheet->setCellValue('G' . $index, $addressArr[2]);
            $sheet->setCellValue('H' . $index, $addressArr[3]);

            // 发件人信息
            $shopConfig = model('app\api\model\wanlshop\ShopConfig')
                ->where(['shop_id' => $this->shop->id])
                ->field('sendPhoneNum,sendCity')
                ->find();
            $sheet->setCellValue('I' . $index, $shopConfig["sendPhoneNum"]);
            $sheet->setCellValue('J' . $index, $shopConfig["sendCity"]);

            $sheet->setCellValue('K' . $index, '');
            $sheet->setCellValue('L' . $index, '');

            $orderGoods = model('app\index\model\wanlshop\OrderGoods')
                ->where(['order_id' => $id])
                ->field('id,title')
                ->find();
            $sheet->setCellValue('M' . $index, $orderGoods["title"]);

            $index++;
        }

        // 设置文档属性
        $spreadsheet->getProperties()
            ->setTitle("Office 2007 XLSX Document")
            ->setSubject("Office 2007 XLSX Document")
            ->setDescription("Document for Office 2007 XLSX");

        // 重定向输出到客户端的浏览器
        $fileName = '商品发货单'.date('Y-m-d H-i-s').'.xlsx'; // 中文文件名

        // 对文件名进行编码
        $encodedFileName = rawurlencode($fileName);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $encodedFileName . '"');
        header('Cache-Control: max-age=0');
        $write = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $write->save('php://output');
    }

    /**
     * 导入发货
     */
    public function importDelivery()
    {
        $file = $this->request->file('file');
        if (!$file) {
            $this->error('文件不能为空');
        }

        try {
            $info = $file->validate(['ext' => 'xls,xlsx'])->move(ROOT_PATH . 'public' . DS . 'uploads'); // 移动到uploads目录并验证文件类型
            if (!$info) {
                $this->error('文件格式错误');
            }

            $filePath = $info->getSaveName(); // 获取文件名（含路径）
            if (strpos($filePath, ".xlsx") !== false) {
                $reader = new Xlsx();
            } else {
                $reader = new Xls();
            }

            $file_real_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . $filePath;
            $spreadsheet = $reader->load($file_real_path); // 加载文件到PhpSpreadsheet对象中

            if (!$spreadsheet) {
                $this->error('文件加载错误');
            }

            $currentSheet = $spreadsheet->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

            if($maxColumnNumber < 14) {
                $this->error('文件格式错误');
            }

            $okCount = 0;
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $id = 0;
                $express_no = "";
                $express_name = "";
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                    if($currentColumn == 1) {
                        // 如果第一列是空，退出
                        if(empty($val)) {

                            unset($info); //释放空间,也可使用 $info = null;
                            //获取完成后，删除文件
                            unlink($file_real_path);

                            $this->success("导入发货成功"+$okCount+"条");
                        }

                        $orderNo = str_replace("SHOP", "", $val);

                        $order = model('app\index\model\wanlshop\Order')
                            ->where(['order_no' => $orderNo, 'shop_id' => $this->shop->id])
                            ->field('id, order_no')
                            ->find();
                        if(!$order) {
                            $this->error('订单不存在');
                        }

                        $id = $order['id'];
                    }

                    if($currentColumn == 14) {
                        $expressArr = explode(',', str_replace("，", ",", $val));
                        $express_name = $expressArr[0];
                        $express_no = $expressArr[1];
                    }
                }

                $order = [];
                $order[] = [
                    'id' => $id,
                    'express_no' => $express_no,
                    'express_name' => $express_name,
                    'delivertime' => time(),
                    'state' => 3
                ];

                //一条一条保存
                $this->model->saveAll($order);
                $okCount++;
            }

            unset($info); //释放空间,也可使用 $info = null;
            //获取完成后，删除文件
            unlink($file_real_path);

            $this->success("导入发货成功数：" . $okCount . "条", "");
        } catch (Exception $exception) {
            $this->error('文件格式错误，第1列为订单号，第11列为运单号，第12列为快递公司');
        }
    }
    
    /**
     * 评论管理
     */
    public function comment()
    {
        return $this->view->fetch('wanlshop/comment/index');
    }
	
	/**
	 * 订单推送消息（方法内使用）
	 * 
	 * @param string order_id 订单ID
	 * @param string state 状态
	 */
	private function pushOrder($order_id = 0, $state = '已发货')
	{
		$order = $this->model->get($order_id);
		$orderGoods = model('app\index\model\wanlshop\OrderGoods')
			->where(['order_id' => $order_id])
			->select();
		$msgData = [];
		foreach ($orderGoods as $goods) {
			$msg = [
				'user_id' => $order['user_id'], // 推送目标用户
				'shop_id' => $this->shop->id, 
				'title' => '您的订单'.$state, // 推送标题
				'image' => $goods['image'], // 推送图片
				'content' => '您购买的商品 '.(mb_strlen($goods['title'],'utf8') >= 25 ? mb_substr($goods['title'],0,25,'utf-8').'...' : $goods['title']).' '.$state, 
				'type' => 'order',  // 推送类型
				'modules' => 'order',  // 模块类型
				'modules_id' => $order_id,  // 模块ID
				'come' => '订单'.$order['order_no'] // 来自
			];
			$msgData[] = $msg;
			$this->wanlchat->send($order['user_id'], $msg);
		}
		$notice = model('app\index\model\wanlshop\Notice')->saveAll($msgData);
	}
}
